package com.skypan.myapplication;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import com.google.gson.Gson;
import com.skypan.myapplication.bean.ImageR;
import com.skypan.myapplication.bean.LoginR;
import com.skypan.myapplication.bean.RegisterR;
import com.skypan.myapplication.http.ImageCallback;
import com.skypan.myapplication.http.LoginCallback;
import com.skypan.myapplication.http.PhotoUtils;
import com.skypan.myapplication.http.RegisterCallback;
import com.skypan.myapplication.widget.Code;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class RegisterActivity extends AppCompatActivity implements View.OnClickListener {


    private final int PICK = 1;
    private static final int IMAGE_RESULT_CODE = 2;
    private TextView txuploadimg;
    private EditText edt_account = null;
    private EditText edt_name = null;
    private EditText edt_pwd1 = null;
    private EditText edt_pwd2 = null;
    private EditText edt_companyid = null;
    private Spinner edt_identity;
    private Button btn_register = null;
    private ImageView back = null;
    private ImageView imguploadimg = null;
    private String fileName;//头像名称
    private String picturePath;//头像路径
    private String url = "http://39.105.165.31:8080/user/register";
    private String Hidove_url = "https://img.abcyun.co/api/upload";
    private String img_url="";//将连接上传到数据库
    private Bitmap bitmap2;
//    private String[] identityarray = {"系统管理员", "监管部门人员", "生产企业管理人员", "生产企业操作人员", "物流公司人员", "接种单位人员", "终端客户",};


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_register);
        initView();



    }

    private void initView(){
        edt_account = findViewById(R.id.edt_register_account);
        edt_name = findViewById(R.id.edt_register_name);
        edt_identity = findViewById(R.id.spiner_identity);
        edt_pwd1 = findViewById(R.id.edt_register_pwd);
        edt_pwd2 = findViewById(R.id.edt_register_repwd);
        edt_companyid = findViewById(R.id.edt_register_companyid);
        btn_register = findViewById(R.id.btn_register);
        back = findViewById(R.id.iv_registeractivity_back);
        txuploadimg = findViewById(R.id.tx_upload_img);
        imguploadimg =  findViewById(R.id.img_upload_img);


        /**
         * 注册页面能点击的就两个地方
         * top处返回箭头、注册按钮
         */
        back.setOnClickListener(this);
        btn_register.setOnClickListener(this);
        txuploadimg.setOnClickListener(this);

    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_registeractivity_back: //返回登录页面
                Intent intent1 = new Intent(this, LoginActivity.class);
                startActivity(intent1);
                finish();
                break;
            case R.id.tx_upload_img:
                Intent intent2=  new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent2, IMAGE_RESULT_CODE);
                break;
            case R.id.btn_register:    //注册按钮
                //获取用户输入的用户名、密码、身份、验证码
                String userAccount = edt_account.getText().toString().trim();
                String userPassword = edt_pwd1.getText().toString().trim();
                String userName = edt_name.getText().toString().trim();
                String companyId = edt_companyid.getText().toString().trim();
                final String[] Identity = {""};
                final String[] identityarray = getResources().getStringArray(R.array.identity);
                edt_identity.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        Identity[0] = identityarray[position];
                    }
                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {
                    }
                });
                String userIdentity =" ";
                if(Identity[0].equals("系统管理员")){
                    userIdentity = "0";
                }else if(Identity[0].equals("监管部门人员")){
                    userIdentity = "1";
                }else if(Identity[0].equals("生产企业管理人员")){
                    userIdentity = "2";
                }else if(Identity[0].equals("生产企业操作人员")){
                    userIdentity = "3";
                }else if(Identity[0].equals("物流公司人员")){
                    userIdentity = "4";
                }else if(Identity[0].equals("接种单位人员")){
                    userIdentity = "5";
                }else if(Identity[0].equals("终端客户")){
                    userIdentity = "6";
                }
                try {
                    uploadimg(bitmap2,userAccount);
                    Toast.makeText(RegisterActivity.this, "img_url:"+img_url, Toast.LENGTH_SHORT).show();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                register(userAccount,userName,userIdentity,userPassword,companyId,img_url);

        }
    }
    public void register(String account,String name,String identity,String password,String companyid,String img_url)
    {
        OkHttpUtils
                .post()//
                .url(url)//
                .addParams("userAccount", account)//
                .addParams("userName", name)//
                .addParams("userIdentity",identity)//
                .addParams("userPassword", password)//
                .addParams("companyId", companyid)//
                .addParams("userPhoto","https://pic.abcyun.co/image/5f099ae6048ce.jpg")//

                .build()//
                .execute(new RegisterCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(RegisterActivity.this,e.getMessage(),Toast.LENGTH_SHORT).show();
                    }


                    public void onResponse(RegisterR response, int id) {

                        if(response.getCode()==0){
//                            Toast.makeText(RegisterActivity.this,response.getMsg(),Toast.LENGTH_SHORT).show();
                            Intent intent6 = new Intent(RegisterActivity.this, LoginActivity.class);
                            startActivity(intent6);
                            finish();

                        }
                        else {
                            Toast.makeText(RegisterActivity.this,response.getMsg(),Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            // 表示 调用照相机拍照
            case PICK:
                if (resultCode == RESULT_OK) {
                    Bundle bundle = data.getExtras();
                    Bitmap bitmap = (Bitmap) bundle.get("data");
                }
                break;
            // 选择图片库的图片
            case IMAGE_RESULT_CODE:
                if (resultCode == RESULT_OK) {
                    Uri uri = data.getData();
                    bitmap2 = PhotoUtils.getBitmapFromUri(uri, this);
                    imguploadimg.setImageBitmap(bitmap2);
                }
                break;
        }
    }
    public File saveFile(Bitmap bm, String fileName) throws IOException {//将Bitmap类型的图片转化成file类型，便于上传到服务器
        String path = Environment.getExternalStorageDirectory() + "/Ask";
        File dirFile = new File(path);
        if(!dirFile.exists()){
            dirFile.mkdir();
        }
        File myCaptureFile = new File(path + fileName);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
        bos.flush();
        bos.close();
        return myCaptureFile;

    }

    public void uploadimg(Bitmap bitmap,String userAccount) throws IOException {//上传图片到Hidove
        File file = saveFile(bitmap,userAccount+"_img");
        if (!file.exists())
        {
            Toast.makeText(RegisterActivity.this, "文件不存在", Toast.LENGTH_SHORT).show();
            return;
        }
        OkHttpUtils
                .postFile()
                .url(Hidove_url)
                .file(file)
                .build()
                .execute(new ImageCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(RegisterActivity.this, "Image Failed:"+e.getMessage(), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(ImageR response, int id) {
                        img_url = response.getData().getUrl().get(0).distribute;
                        Toast.makeText(RegisterActivity.this, response.getData().getUrl().get(0).distribute, Toast.LENGTH_SHORT).show();
                    }
                });
    }


}
